'use strict';

var fs = require('fs');
var path = require('path');
var router = require('koa-router')();

function getEachControllerFiles(dir){
    var files = fs.readdirSync(dir);

    var controllerFiles = files.filter((name) => {
        return name.endsWith('.js') && name !== 'index.js';
    });

    return controllerFiles;
}

function registeRoutes(files){
    files.forEach(item => {
        var tmpFile = path.join(__dirname, item);
        var tmpRoutes = require(tmpFile);
        for (var x in tmpRoutes) {
            var valueArr=tmpRoutes[x];
            var type = valueArr[0];
            if (type === 'get') {
                if(valueArr.length===2){
                    var fn=valueArr[1];
                    router.get(x, fn);
                }else{
                    var auth=valueArr[1];
                    var fn=valueArr[2];
                    router.get(x,auth,fn);
                }
            }
            else if (type === 'post') {
                if(valueArr.length===2){
                    var fn=valueArr[1];
                    router.post(x, fn);
                }else{
                    var auth=valueArr[1];
                    var fn=valueArr[2];
                    router.post(x,auth,fn);
                }
            }
            else if (type === 'put') {
                if(valueArr.length===2){
                    var fn=valueArr[1];
                    router.put(x, fn);
                }else{
                    var auth=valueArr[1];
                    var fn=valueArr[2];
                    router.put(x,auth,fn);
                }
            }
            else if (type === 'delete') {
                if(valueArr.length===2){
                    var fn=valueArr[1];
                    router.delete(x, fn);
                }else{
                    var auth=valueArr[1];
                    var fn=valueArr[2];
                    router.delete(x,auth,fn);
                }
            }
        }
    })
}




module.exports = function () {
    var defaultControlleDir = __dirname;

    var controllerFiles=getEachControllerFiles(defaultControlleDir);

    registeRoutes(controllerFiles);   


    return router.routes();
}